var myChart = "";
var userArray = new Array(4);
var toDoWorkArray = new Array(4);
var doingWorkArray = new Array(4);
var publishWorkArray = new Array(4);
var doneWorkArray = new Array(4);
var selectSprintState=true;
var ProductVersionState=true;
var ProductState=true;
var OSproductName = undefined;
var OSProductVersionID = undefined;
var OSSprintState = false;
$(document).ready(function () {
    initClickProduct();
    selectDate("startDate");
    selectDate("endDate");
});
function initClickProduct(){
    var ProductVersionID = $("#iframe",parent.document).attr("name");
    if(ProductVersionID != undefined && ProductVersionID != ""){
        ProductState = false;
        ProductVersionState = false;
        selectSprintState = false;
        $.post("getProductNameByProductVersionID",{"ProductVersionID":ProductVersionID},function (result) {
            if(result.state == 1 ){
                var list = result.data;
                OSproductName = list[0].productName;
                OSProductVersionID = ProductVersionID;
                OSSprintState = true;
                doGetAllProducts('productPackUp', 'backLogProducts', 'productUnfurled');
            }else{
                showMessage("获取数据失败");
            }
        })
        $("#iframe",parent.document).attr("name","");
    }else{
        doGetAllProducts('productPackUp', 'backLogProducts', 'productUnfurled');
    }
}
function doGetAllProducts(OneElement, TwoElement, ThreeElement) {
    $.post("doGetAllProducts", function (result) {
        if (result.state == 1) {
            var list = result.data;
            var backLogProducts = $("#backLogProducts");
            backLogProducts.empty();
            for (var i in list) {
                var productInitials = list[i].productName.substring(0, 1);
                backLogProducts.append('<div class="productList">'+
                    '<span class="productLabel">'+productInitials+'</span>'+
                    '<span id="'+list[i].productName+'1" class="productName commonBlueFont" onMouseOver="mmigration(\''+ list[i].productName +'1\')" onMouseOut="shiftOut()"' +
                    ' onclick="doGetProductVersion(\''+list[i].productId+'\',\''+list[i].productName+'1\',\''+list[i].productName+'2\')">'+list[i].productName+
                    '<img  src="../PM/images/arrow1.png"  />'+
                    '</span>'+
                    '<span id="'+list[i].productName+'2" class="productName commonBlueFont" onMouseOver="mmigration(\''+ list[i].productName +'2\')" onMouseOut="shiftOut()" onclick="toCloseVersions(\''+list[i].productId+'\',\''+list[i].productName+'2\',\''+list[i].productName+'1\')" hidden="hidden">'+list[i].productName+
                    '<img  src="../PM/images/arrow2.png"/>' +
                    '</span>'+
                    '<div class="productEditions" id="'+list[i].productId+'"></div></div>');
            }
            $("#" + ThreeElement).hide();
            $('#' + OneElement).show();
            $('#' + TwoElement).show();
        } else {
            showMessage("获取产品失败");
        }
        if(ProductState == true){
            ProductState = false;
            getProductVersion();
        }
        if(OSproductName != undefined){
            $("#"+OSproductName+"1").click();
            OSproductName = undefined;
        }
    });
}
function toCloseVersions(productId,OneElement,TwoElement){
    $("#"+OneElement).hide();
    $("#"+TwoElement).show();
    $("#"+productId).hide();
}
function getProductVersion() {
    $("#backLogProducts .productList").first().find('.productName').first().click();
}
function doGetProductVersion(productId,OneElement,TwoElement) {
    var $div = $("#"+productId);
    $div.show();
    $div.empty();
    var params = {"productId": productId};
    $.post("doGetProductVersions", params, function (result) {
        if (result.state==1) {
            if(result.data.length>0){
                var list = result.data;
                for (var i in list) {
                    $div.append('<div>' +
                        '<p class="commonBlueFont" id=\'v' + list[i].productVersionID + '\' onMouseOver="mmigration(\'v'+ list[i].productVersionID +'\')" onMouseOut="shiftOut()"' +
                        ' onclick=doGetSprint(\'v' + list[i].productVersionID + '\')>'+ "+ " + list[i].productVersionName + '</p>' +
                        '<p class="commonBlueFont" id=\'close' + list[i].productVersionID + '\' onMouseOver="mmigration(\'close'+ list[i].productVersionID +'\')" onMouseOut="shiftOut()"' +
                        ' onclick=closeSprint(this) hidden="hidden" >'+ "- " + list[i].productVersionName + '</p>' +
                        '<div id="sprintMessage"></div></div>');
                }
                $("#" + OneElement).hide();
                $("#" + TwoElement).show();
            }else{
                showMessage("请先添加版本","1","toAddProduct(\'"+productId+"\')");
            }
        } else {
            showMessage("获取产品版本信息失败");
        }
        if(ProductVersionState == true){
            ProductVersionState = false;
            getSprint();
        }
        if(OSProductVersionID != undefined){
            $("#v"+OSProductVersionID).click();
        }
    });
}
function closeSprint(OneElement){
    $(OneElement).hide();
    $(OneElement).next().hide();
    $(OneElement).prev().show();
}
function getSprint() {
    $("#backLogProducts .productList .productEditions div p").first().click();
}
function doGetSprint(productVersionID) {

    $("#"+productVersionID).next().show();
    $("#"+productVersionID).hide();

    var sprintMessage = $("#"+productVersionID).next().next();
        sprintMessage.show();
        sprintMessage.empty();

    productVersionID=productVersionID.substring(1,productVersionID.length);
    var productVersionId = productVersionID;
    var AllWork='';
    var DoneWork='';
        $.post("doGetSprint", {"productVersionID": productVersionId}, function (result) {
            if (result.state == 1) {
                var list = result.data;
                for (var i in list) {
                    AllWork=list[i].allWork;
                    DoneWork=list[i].doneWork;
                    var taskState='';
                    if(AllWork){
                        if(DoneWork<AllWork){
                            taskState="<span id='doing'>进行中<span>";
                        }else if(DoneWork==AllWork){
                            taskState="<span id='complete'>完成<span>";
                        }
                    }

                    sprintMessage.append('<p class="commonBlueFont" id="' + list[i].sprintID + '" onMouseOver="mmigration(\''+ list[i].sprintID +'\')" onMouseOut="shiftOut()" ' +
                        'onclick=getSprintBySprintID(\''+list[i].sprintID+'\')>'
                        + list[i].sprintName +taskState+'</p>');
                }
                if (list.length == 0) {
                    sprintMessage.append('<u><span class="commonBlueFont" id="' + productVersionId + 'a" onMouseOver="mmigration(\''+ productVersionId +'a\')" onMouseOut="shiftOut()" onclick=showAddSprint(\'v'+ productVersionId + '\',\'addData\')>添加Sprint</span></u>');
                }else{
                    sprintMessage.append('<u><span  class="commonBlueFont" id="' + productVersionId + 'a" onMouseOver="mmigration(\''+ productVersionId +'a\')" onMouseOut="shiftOut()" onclick=showAddSprint(\'v'+ productVersionId + '\',\'addData\')>添加Sprint</span></u>');
                }
            } else {
                showMessage("获取产品版本信息失败");
            }
            if(selectSprintState == true){
                selectSprintState = false;
                getSprintMessage();
            }
            if(OSSprintState == true){
                if(OSProductVersionID != undefined){
                    $("#"+OSProductVersionID+"a").click();
                    OSProductVersionID = undefined;
                }
                selectSprintState = false;
            }
        });
}
function getSprintMessage(){
    $("#backLogProducts .productList .productEditions div div p").first().click();
}
function getSprintBySprintID(sprintID) {

    $("#sprintCompletion").show();
    $("#backLogModular").show();
    $(".activeP").removeClass("activeP");
    $("#"+sprintID).addClass("activeP");

    var sprintCompletion = $("#sprintCompletion");
    sprintCompletion.attr("name", sprintID);
    sprintCompletion.empty();

        $.post("doGetProductVersionID", {"sprintID": sprintID}, function (result) {
            if (result.state == 1) {
                var list = result.data;
                for(var i in list){
                    sprintCompletion.append(
                        '<div class="col-sm-12" style="margin-bottom:35px;">' +
                            '<span id="sprintName">' + list[i].sprintName + '</span>' +
                            '<a id="deleteSprint" onclick=showMessage(\"确定要删除吗\",\"1\",\"deleteSprint(\'' + sprintID + '\',\'' + list[i].productVersionID+ '\')\")>删除</a>' +
                            '<a id="updateSprint" onclick="showAddSprint(\'' + sprintID + '\',\'updateData\',\'' + list[i].productVersionID + '\')">修改</a> &nbsp; ' +
                        '</div>');
                }
            }else{
                showMessage("获取sprint的版本号失败");
            }
            $.post("doGetMessageBySprintId", {"sprintID": sprintID}, function (result) {
                if (result.state == 1) {
                    var list = result.data;
                    for (var i in list) {
                        if (i == list.length - 1) {
                            var surplusWork = list[i].surplusWork;
                            if (surplusWork < 0) {
                                surplusWork = "超出"+(-(surplusWork))+"天";
                            }else{
                                surplusWork = "剩余"+surplusWork+"天";
                            }
                            var complete=list[i].complete || "0%";
                            var fontColor="";
                            if(complete=="0%"){
                                fontColor="color:#00000085;";
                            }
                            sprintCompletion.append(
                                '<div class="progress">' +
                                    '<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:' + complete + ';'+fontColor+'">' + complete + '' +
                                    '</div>' +
                                '</div>' +
                                '<div class="col-sm-12">' +
                                    '<span id="timeSpan">时间 : ' +
                                        '<a id="startTime">' + list[i].sprintStartDTTM + '</a> 至 ' +
                                        '<a id="EndTime">' + list[i].sprintEndDTTM + '</a>' +
                                    '</span>' +
                                    '<span id="completionSituation">完成情况 : ' +
                                         '<a>已过期' + list[i].overdueWork + '天 ，' + surplusWork + '</a>' +
                                    '</span>' +
                                '</div>');
                        }
                    }
                 updateCurrentTitle(sprintID);
                } else {
                    $("#backLogModular").hide();
                    showMessage("获取sprint失败");
                }
            })
        })
    $.post("doGetBackLogStateBySprintId", {"sprintID": sprintID}, function (result) {
        if (result.state == 1) {
            changeEchart(result.data);
        } else {
            showMessage("获取每人任务状态失败");
        }
    })
    $.post("doGetBackLogCountByEveryDay", {"sprintID": sprintID}, function (result){
        if (result.state == 1) {
            changeLinearGraph(result.data);
        } else {
            showMessage("获取BackLog任务量失败");
        }
    })
    doneEffect();
}
function updateCurrentTitle(sprintID){
    $.post("doUpdateCurrentTitle", {"sprintID": sprintID}, function (result) {
            if (result.state == 1) {
             var list = result.data;
                var currentTitle = $("#sprintName");
                currentTitle.empty();
                currentTitle.html(list[0].productName+"-"+list[0].productVersionName+"-"+list[0].sprintName);
            } else {
                showMessage("获取当前页面位置失败");
            }
     });
}
function deleteSprint(sprintId,productVersionID){
    $.post("doDeleteSprintById", {"sprintID": sprintId}, function (result){
        if (result.state == 1) {
            doGetSprint("v"+productVersionID);
            showHideModal();
            $("#sprintCompletion").hide();
            $("#backLogModular").hide();
            showMessage("删除成功");
        } else {
            showMessage("删除Sprint失败");
        }
    })
}
function changeEchart(list) {
     $("#barGraph").empty();

    if (list == undefined || list == "") {
      $("#barGraph").parent().hide();
        return;
    }
    $("#barGraph").parent().show();
    userArray = [], toDoWorkArray = [], doingWorkArray = [], publishWorkArray = [], doneWorkArray = [];
    for (var i = 0; i < list.length; i++) {
        userArray[i] = list[i].UserName;
        toDoWorkArray[i] = list[i].toDoWork;
        doingWorkArray[i] = list[i].doingWork;
        publishWorkArray[i] = list[i].publishWork;
        doneWorkArray[i] = list[i].doneWork;
    }
    myChart = echarts.init(document.getElementById('barGraph'));
    option = {
        title: {
            text: '负责人任务状态柱状图',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            right: '5%',
            data: ['待办', '进行', '完成', '发布']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: userArray
            }
        ],
        yAxis: [
            {
                type: 'value',
            }
        ],
        series: [
            {
                name: '待办',
                type: 'bar',
                stack: '统计',
                barWidth: '30px',
                data: toDoWorkArray,
            },
            {
                name: '进行',
                type: 'bar',
                stack: '统计',
                barWidth: '30px',
                data: doingWorkArray,
            },
            {
                name: '完成',
                type: 'bar',
                stack: '统计',
                barWidth: '30px',
                data: doneWorkArray,
            },
            {
                name: '发布',
                type: 'bar',
                stack: '统计',
                barWidth: '30px',
                data: publishWorkArray,
            },
        ]
    };
    myChart.setOption(option);
}
function changeLinearGraph(list) {
    $("#urnoutDiagram").empty();

    if (list == undefined || list == "") {
    $("#urnoutDiagram").parent().hide();
        return;
    }
    $("#urnoutDiagram").parent().show();
    var workDate = new Array(list.length);
    var date = new Array(list.length);
    for (var i = 0; i < list.length; i++) {
        workDate[i] = list[i].SprintWorkDate;
        date[i] = list[i].Date;
    }
    myChart = echarts.init(document.getElementById('urnoutDiagram'));
    option = {
        title: {
            text: '任务工时燃尽图',
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: true,
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                dataView: {readOnly: false},
                magicType: {type: ['line', 'bar']},
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: date
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}'
            }
        },
        series: [
            {
                type: 'line',
                data:workDate,
                markLine: {
                    lineStyle: {
                        normal: {
                            type: 'dashed'
                        }
                    },
                    data: [
                        [{type: 'max'}, {type: 'min'}]
                    ]
                }
            }
        ]
    };
    myChart.setOption(option);

}
function showAddSprint(productVersionID,eventType,ThreeElement) {

    $(".addBackLog").show();
    $(".addBackLog").attr("name", productVersionID);
    $("#workName").val("");
    $("#workNameSign").val("");
    $("#txtBeginDate").val("");
    $("#txtEndDate").val("");
    $("#workDescribe").val("");
    if(eventType=="addData"){
        $(".addBackLogTitle").html("添加 Sprint");
        $("#addBackLogMsgSure").attr('onclick','addSprintMsgSure()')
    }
    if(eventType=="updateData"){
        $(".addBackLog").attr("id",ThreeElement);
        $(".addBackLogTitle").html("修改 Sprint");
        $.post("doGetSprintBySprintID",{"sprintID":productVersionID},function(result){
            if(result.state==1){
               var list=result.data;
                $("#workName").val(list[0].sprintName);
                $("#workNameSign").val(list[0].sprintNameSign);
                $("#workDescribe").val(list[0].sprintDescription);
                $("#txtBeginDate").val(formatDate(list[0].sprintStartDTTM));
                $("#txtEndDate").val(formatDate(list[0].sprintEndDTTM));
                $("#addBackLogMsgSure").attr('onclick','updateSprint()')
            }else{
                showMessage("获取Sprint失败");
            }
        })
    }
}
function updateSprint(){
    $(".addBackLog").hide();
    var params = {
        "SprintName": $("#workName").val(),
        "SprintNameSign": $("#workNameSign").val(),
        "SprintStartDTTMStr": $("#txtBeginDate").val(),
        "SprintEndDTTMStr": $("#txtEndDate").val(),
        "SprintID":$(".addBackLog").attr("name"),
        "SprintStatus": $("input[name='workType']:checked").val() == 1 ? true : false,
        "SprintDescription": $("#workDescribe").val()
    };
    $.post("doUpdateSprintBySprintID", params, function (result) {
        if (result.state == 1) {
            showMessage("修改成功");
            doGetSprint("v"+$(".addBackLog").attr("id"));
            getSprintBySprintID($(".addBackLog").attr("name"));
        } else {
            showMessage("修改Sprint失败");
        }
    })
}
function addSprintMsgSure() {

    var productVersionID=$(".addBackLog").attr("name");
    var workName = $("#workName").val();
    var workNameSign = $("#workNameSign").val();
    var txtBeginDate = $("#txtBeginDate").val();
    var txtEndDate = $("#txtEndDate").val();
    productVersionID=productVersionID.substring(1,productVersionID.length);

    if(workName == undefined || workName == ""){
        showMessage("Sprint名称不能为空");
        return;
    }
    if(workNameSign == undefined || workNameSign == ""){
        showMessage("Sprint简称不能为空");
        return;
    }
    if(txtBeginDate == undefined || txtBeginDate == ""){
        showMessage("开始时间不能为空");
        return;
    }
    if(txtEndDate == undefined || txtEndDate == ""){
        showMessage("结束时间不能为空");
        return;
    }
    $(".addBackLog").hide();
    var params = {
        "SprintName": $("#workName").val(),
        "SprintNameSign": $("#workNameSign").val(),
        "SprintStartDTTMStr": $("#txtBeginDate").val(),
        "SprintEndDTTMStr": $("#txtEndDate").val(),
        "ProductVersionID": productVersionID,
        "SprintStatus": $("input[name='workType']:checked").val() == 1 ? true : false,
        "SprintDescription": $("#workDescribe").val()
    };
    $.post("doAddSprint", params, function (result) {
        if (result.state == 1) {
            showMessage("添加成功");
            doGetSprint($(".addBackLog").attr("name"));
        } else {
            showMessage("添加Sprint失败");
        }
    })
}
function hideSprintMsg() {
    $(".addBackLog").hide();
}
